/**
 * module:  顶部牧场，养殖舍获取
 * avator:   渣
 * table:  nc_pasture,nc_house
 */
var express = require('express');
var router = express.Router();
var zSend = require('./controller');
const fs = require('fs');

const db = require('../../../db/db');

router.get('/getCondition',(req,res,next)=>{
    const sql = `
        select F_Id ,F_Title from nc_pasture
    `
    const sql2 = `
        select F_Id ,F_Title from nc_house
    `
    db.query(sql,(err,data)=>{
        if(!data){
            res.send(zSend('服务器内部错误',500))
        }else{
            db.query(sql2,(err,data2)=>{
                if(!data2){
                    res.send(zSend('服务器内部错误',500))
                }else{
                    res.send(zSend({
                        pasture:data,
                        house:data2
                    }))
                }
            })
        }
    })
});

//根据id查询牛名称
router.get('/gitCowById', (req, res, next) => {
    const { F_Id } = req.query;
    if(!F_Id){
        res.send(zSend('参数错误', 400))
    }
    const sql = `
        select F_Title from nc_livestock where F_Id = '${F_Id}'
    `
    db.query(sql, (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        }else {
            res.send(zSend(data[0]))
        }
    })
});

router.post('/imgUpload', (req, res) => {
    let oldName = req.files[0].filename;//获取名字
    let originalname=req.files[0].originalname;//originnalname其实就是你上传时候文件起的名字
    
    let newName = Date.now()+'.'+originalname.split('.')[1];
    fs.renameSync('./public/upload/'+oldName, './public/upload/'+newName); //重命名
    
    res.send(zSend('/upload/'+newName));
});

module.exports = router;